// pages/cart/component/cart.js
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/store/userstore'
import { reqCartList, reqUpdateChecked, reqCheckAllStatus, reqAddCart, reqDelCartGoods } from '@/api/cart'
//导入debounce防抖方法
import { debounce } from 'miniprogram-licia'
//导入让删除滑块自动弹回的behavior
import { swipeCellBehavior } from '@/behaviors/swipeCell'
const computedBehavior = require('miniprogram-computed').behavior

ComponentWithStore({
  behaviors: [ computedBehavior, swipeCellBehavior ],
  //定义计算属性
  computed:{
    //判断是否全选，控制全选按钮的选中效果
    //计算属性会被挂载到data对象中
    selectAllStatus( data ){
      return (
        data.cartList.length !== 0 && data.cartList.every((item) => item.isChecked === 1) 
      )
    },
    totalPrice(data){
      let totalPrice = 0
      data.cartList.forEach((item) => {
        if(item.isChecked === 1){
          totalPrice += item.count * item.price
        }
      })
      return totalPrice 
    }
  },
  storeBindings:{
    store: userStore,
    fields: ['token']
  },
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeBuyNum: debounce(async function(event){
      //console.log(event)
      const newBuyNum = event.detail > 200 ? 200 : event.detail
      const {id, index, oldbuynum } = event.target.dataset
      const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
      const regRes = reg.test(newBuyNum)
      if(!regRes){
        //console.log(oldbuynum)
        this.setData({
          [`cartList[${index}].count`] : oldbuynum
        })
        return
      }
      const discount = newBuyNum - oldbuynum
      if(discount === 0) return
      const res = await reqAddCart({goodsId: id, count: discount})
      if(res.code === 200){
        this.setData({
          [`cartList[${index}].count`]: newBuyNum
        })
      }
   }, 500),
    //实现全选和全不选效果
    async selectAllStatus(event){
      const { detail } = event
      const isChecked = detail ? 1 : 0
      const res = await reqCheckAllStatus(isChecked) 
      if(res.code === 200){
        //this.showTipGetList()
        const newCartList = JSON.parse(JSON.stringify(this.data.cartList))
        newCartList.forEach((item) => {item.isChecked=isChecked})
        this.setData({
          cartList: newCartList
        })
      }
    },
    async showTipGetList(){
      const { token } = this.data
      if(!token){
        this.setData({
          emptyDes: '您尚未登陆，点击登陆获取更多权益',
          cartList: []
        })
        return
      }
      const {code, data:cartList } = await reqCartList()
      if(code === 200){
        this.setData({
          cartList,
          emptyDes: cartList.length === 0 && '还没有添加商品，快去添加商品吧'
        })
      }
    },
    onShow(){
      this.showTipGetList()
    },
    async updateChecked(event){
      const { detail } = event
      const { id, index } = event.target.dataset
      const isChecked = detail ? 1 : 0
      const res = await reqUpdateChecked(id, isChecked)
      if(res.code === 200){
        //this.showTipGetList()
        this.setData({
          [`cartList[${index}].isChecked`] : isChecked
        })
      }
    },
    //删除
    async delCartGoods(event){
      console.log(event)
      const { id } = event.currentTarget.dataset
      const modalRes = await wx.modal({
        content: '您确认删除该商品吗？'
      })
      console.log(id)
      if(modalRes){
        await reqDelCartGoods(id)
        this.showTipGetList()
      }
    },
    onHide(){
      this.onSwipeCellCommonClick()
    },
    toOrder(){
      if(this.data.totalPrice === 0){
        wx.toast({title:'请选择需要购买的商品'})
        return
      }
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/detail/detail',
      })
    }
  }
})

